package com.lyl.security.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.lyl.security.dto.LoginDetails;
import com.lyl.security.dto.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Mr.Luo
 * @date 2022-09-19 11:17
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    List<User> userList = ListUtil.toList(
            new User("张三", "$2a$10$ynhFOMAhoKeqQLgOZspZ6uJGA6Zq8BMlVjI.i3kpEr.TxoopLN1hC", ListUtil.toList("hello")),
            new User("李四", "$2a$10$ynhFOMAhoKeqQLgOZspZ6uJGA6Zq8BMlVjI.i3kpEr.TxoopLN1hC", ListUtil.toList("admin"))
    );

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getByUsername(username);
        Assert.notNull(user, () -> new UsernameNotFoundException("找不到对应的用户名"));
        return new LoginDetails(user,user.getPerms());
    }

    public User getByUsername(String username) {
        return userList.stream().filter(user -> ObjectUtil.equals(username, user.getUsername()))
                .findFirst().get();
    }
}
